/*
 * @(#)FilterCacheProxy.java    0.5 08/29/2009
 */
package org.miao.catstorage;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 过滤器缓存代理
 * @author Miao
 * @version 0.5
 * @since 0.5
 */
public class FilterCacheProxy implements Filter {

    /**
     * 缓存
     */
    private final Cache<String, String> cache;
    /**
     * 过滤器
     */
    private final Filter filter;
    /**
     * 日志
     */
    private static final Log log = LogFactory.getLog(Storage.class);

    /**
     * 构造方法
     * @param cache 缓存
     * @param filter 过滤器
     * @since 0.5
     */
    public FilterCacheProxy(Cache<String, String> cache, Filter filter) {
        this.cache = cache;
        this.filter = filter;
    }

    public String filter(String statement, List<String> parameters) {
        String key = getKey(statement, parameters);
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            String value = filter.filter(statement, parameters);
            log.info("statement: " + value);
            cache.put(key, value);
            return value;
        }
    }

    private String getKey(String statement, List<String> parameters) {
        StringBuilder sb = new StringBuilder(50);
        sb.append(statement);
        for (String parameter : parameters) {
            sb.append(parameter);
        }
        return sb.toString();
    }
}
